var gulp = require('gulp');
var runSequence = require('run-sequence');
var $ = require('gulp-load-plugins')(gulp);
var liveServer = require("live-server");


var params = {
    port: 8181, // Set the server port. Defaults to 8080.
    host: "0.0.0.0", // Set the address to bind to. Defaults to 0.0.0.0 or process.env.IP.
    root: "./dist",
    open: true, // When false, it won't load your browser by default.re
    file: "index.html", // When set, serve this file for every 404 (useful for single-page applications)
    wait: 1000, // Waits for all changes, before reloading. Defaults to 0 sec.
    mount: [['/components', './node_modules']], // Mount a directory to a route.
    logLevel: 2, // 0 = errors only, 1 = some, 2 = lots
    middleware: [function(req, res, next) { next(); }] // Takes an array of Connect-compatible middleware that are injected into the server middleware stack
};

gulp.task('default', ['bulid'], function(){
     gulp.watch(['./*.html','./css/*.css','./js/*.js'],['bulid'])
});

//清空
gulp.task('clean',function(cb){
	return gulp.src('./dist/')
  	.pipe($.clean())
})
//压缩图片
gulp.task('Imagemin', function () {
    gulp.src('./img/*.{png,jpg,gif,ico}')
        .pipe($.imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],//不要移除svg的viewbox属性
        }))
        .pipe(gulp.dest('dist/img'))
});


//压缩css
gulp.task('cssmin',function(){
	return gulp.src(['./css/*.css','dist/rev/img/*.json'])
		.pipe($.revCollector({
			 replaceReved: true
		}))
		.pipe($.rev())
		.pipe(gulp.dest('dist/css/'))
		.pipe($.rev.manifest())
        .pipe(gulp.dest('./dist/rev/css'))

})


//压缩js
gulp.task('jsmin',function(){
	return gulp.src(['./js/zepto.js', './js/sm.min.js', './js/sm-extend.min.js','./js/main.js','./dist/rev/img/*.json','./dist/rev/css/*.json'])
		.pipe($.revCollector({
			 replaceReved: true
		}))
		.pipe($.uglify())
		.pipe($.concat('main.js'))
		.pipe($.rev())
		.pipe(gulp.dest('dist/js/'))
		.pipe($.rev.manifest())
        .pipe(gulp.dest('./dist/rev/js'))
})

gulp.task('htmlmin',function(){
	return gulp.src(['./*.html','./dist/rev/img/*.json','./dist/rev/css/*.json','./dist/rev/js/*.json'])
		.pipe($.revCollector({
			 replaceReved: true
		}))
		.pipe($.htmlmin({collapseWhitespace: true}))
		.pipe(gulp.dest('dist/'))

})

gulp.task('server',function(){
	liveServer.start(params);
})

gulp.task('bulid',function(done){
	runSequence('clean','Imagemin','cssmin', 'jsmin','htmlmin','server',done)
})
